/*
 * @Description  :
 * @Version      : 1.0
 * @Author       : Shiming
 * @Date         : 2021-12-15 13:17:42
 * @LastEditors  : Shiming
 * @LastEditTime : 2022-03-24 19:17:10
 * @FilePath     : \\tms-obc-web\\src\\app\\routes\\order-management\\modal\\vehicle\\update-freight\\update-freight.component.ts
 * Copyright (C) 2022 huzhenhong. All rights reserved.
 */
import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { SFComponent, SFNumberWidgetSchema, SFSchema, SFTextareaWidgetSchema, SFUISchema } from '@delon/form';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { Subscription } from 'rxjs';
import { OrderManagementService } from '../../../services/order-management.service';

@Component({
  selector: 'app-order-management-vehicle-update-freight',
  templateUrl: './update-freight.component.html',
  styleUrls: ['./update-freight.component.less']
})
export class VehicleUpdateFreightComponent implements OnInit {
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  schema: SFSchema = {};
  ui: SFUISchema = {};
  isVisible = false;
  modalcontent = '';

  aggreechecked = false;

  @Input()
  data: any;

  dataJSON: any;

  calculateSub!: Subscription;

  constructor(private modal: NzModalRef, private msgSrv: NzMessageService, public service: OrderManagementService) {}

  ngOnInit(): void {
    console.log(this.data)
    this.dataJSON = JSON.stringify(this.data)
    console.log(this.dataJSON)
    this.initSF(this.data);
  }
  initSF(data: any) {
    const info = {
      prePay: data.list?.filter((item: any) => item.costCode === 'PRE')[0],
      toPay: data.list?.filter((item: any) => item.costCode === 'RECE')[0],
      receiptPay: data.list?.filter((item: any) => item.costCode === 'BACK')[0]
    };
    this.schema = {
      properties: {
        prePay: {
          type: 'number',
          title: '预付',
          default: info.prePay?.price || 0,
          minimum: 0,
          maximum: 99999,
          readOnly: info.prePay?.paymentStatus === '2' || info.prePay?.paymentStatus === '4',
          ui: {
            prefix: '￥',
            widgetWidth: 200,
            precision: 2,
            change: (val: any) => this.changeNumVal()
          } as SFNumberWidgetSchema
        },
        toPay: {
          type: 'number',
          title: '到付',
          default: info.toPay?.price || 0,
          minimum: 0,
          maximum: 99999,
          readOnly: info.toPay?.paymentStatus === '2' || info.toPay?.paymentStatus === '4',
          ui: {
            prefix: '￥',
            widgetWidth: 200,
            precision: 2,
            change: (val: any) => this.changeNumVal()
          } as SFNumberWidgetSchema
        },
        // oilCardPay: {
        //   type: 'number',
        //   title: '油卡',
        //   default: 0.0,
        // minimum:0,
        //   readOnly: this.i.oilCardPayStatus === '1' || this.i.oilCardPayStatus === '3',
        //   ui: {
        //     prefix: '￥',
        //     widgetWidth: 200,
        //     precision: 2,
        //     change: (val: any) => this.changeNumVal()
        //   } as SFNumberWidgetSchema
        // },
        receiptPay: {
          type: 'number',
          title: '回单付',
          maximum: 99999,
          default: info.receiptPay?.price || 0,
          minimum: 0,
          readOnly: info.receiptPay?.paymentStatus === '2' || info.receiptPay?.paymentStatus === '4',
          ui: {
            prefix: '￥',
            widgetWidth: 200,
            precision: 2,
            change: (val: any) => this.changeNumVal()
          } as SFNumberWidgetSchema
        },
        changeCause: {
          type: 'string',
          title: '变更原因',
          maxLength: 100,
          ui: {
            widget: 'textarea',
            autosize: { minRows: 3, maxRows: 6 }
          } as SFTextareaWidgetSchema
        }
      },
      required: ['changeCause']
    };
    this.ui = {
      '*': {
        spanLabelFixed: 100,
        grid: { span: 16 }
      }
    };
  }

  save(value: any): void {
    if (this.data.isFreightChangeApplication) {
      this.service.msgSrv.error('变更申请未处理，请勿重复申请！');
      return;
    }
    if (!this.save) {
      this.service.msgSrv.error('请填写必填项！');
      return;
    }
    this.service.request(this.service.$api_get_insertFreightChangeWhole, this.getParams()).subscribe(res => {
      if (res) {
        this.modal.destroy(true);
        this.service.msgSrv.success('变更运费成功');
      }
    });
  }

  close(): void {
    this.modal.destroy(false);
  }
  /**
   * 更新数字框
   *
   */
  changeNumVal() {
    if (this.calculateSub) {
      this.calculateSub.unsubscribe();
    }
    console.log(this.getParams());
    
    this.calculateSub = this.service.request(this.service.$api_getWholeSurchargeDetail, this.getParams()).subscribe((res: any) => {
      if (res) {
        Object.assign(this.data, {
          totalAmount: res.totalAmount,
          totalFreight: res.totalFreight,
          freight: res.freight,
          surcharge: res.surcharge
        });
      }
    });
    // this.tranPrice = this.sf?.value.prePay + this.sf?.value.toPay + this.sf?.value.oilCardPay + this.sf?.value.receiptPay;
    // this.totalPrice = this.sf?.value.prePay + this.sf?.value.toPay + this.sf?.value.oilCardPay + this.sf?.value.receiptPay + this.otherPrice;
  }

  getParams() {
    const editItems = this.data.list?.filter((info: any) => info.toPay?.paymentStatus !== '2' && info.toPay?.paymentStatus !== '4');
    editItems.forEach((item: any) => {
      switch (item.costCode) {
        case 'PRE':
          item.price = this.sf?.value.prePay;
          break;
        case 'RECE':
          item.price = this.sf?.value.toPay;
          break;
        case 'BACK':
          item.price = this.sf?.value.receiptPay;
          break;
        default:
          break;
      }
    });

    const params = {
      billId: this.data.id,
      dtos: editItems,
      changeCause: this.sf?.value.changeCause
    };
    return params;
  }
  agreement() {

    const param = {
      billId: this.data.id,
      pre: this.sf?.value.prePay,
      rece: this.sf?.value.toPay,
      back: this.sf?.value.receiptPay,
      total: this.data.totalFreight,
      freightAmount: this.data.totalAmount,
    }
    this.service.request(this.service.$api_getSupplementaryAgreement, param).subscribe(res => {
      if (res) {
        this.modalcontent = res.contractContent;
        this.isVisible = true;
      }
    });

  }


  handleCancel() {
    this.isVisible = false;
  }
  handleOK() {
    this.isVisible = false;
  }
}
